//
//  JCConversationListViewController.swift
//  JChat
//
//  Created by JIGUANG on 2017/2/16.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import JMessage
import YHPopupView
import JXPagingView
import JXCategoryView
import MTCategory
import YPNavigationBarTransition
import JXSegmentedView

class JCConversationListViewController: BaseViewController {
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    var datas: [JMSGConversation] = []

    //MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        //addEnviromentButton()
        _init()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if isConnecting {
            titleTips.text = "连接中"
            titleTipsView.isHidden = false
        } else {
            titleTipsView.isHidden = true
        }
        _getConversations()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        titleTipsView.isHidden = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        JCVerificationInfoDB.shareInstance.quaryRequestCountData(verType: MTRequestVerifyType.single.rawValue) {[weak self] (count) in
            guard let weakSelf = self else { return }
            weakSelf.friendRequestView.setRedPoint(pointValue: count)
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        JMessage.remove(self, with: nil)
    }
    
    fileprivate var isConnecting = false
    
    lazy var friendRequestView: MTDiscoverFriendRequestView = {
        let r: MTDiscoverFriendRequestView = MTDiscoverFriendRequestView(title: "待处理请求", subTitle: "我的好友请求", type: .single)
        r.delegate = self
        return r
    }()
    
    private lazy var addButton = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
    //private lazy var searchController: JCSearchController = JCSearchController(searchResultsController: BaseNavController(rootViewController: JCSearchResultViewController()))
    //private lazy var searchView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 36))
    fileprivate lazy var tableview: UITableView = {
        var tableview = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height))
        tableview.delegate = self
        tableview.dataSource = self
        tableview.backgroundColor = UIColor.theme.background
        tableview.register(JCConversationCell.self, forCellReuseIdentifier: "JCConversationCell")
        tableview.separatorStyle = .none
        
        tableview.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        tableview.showsVerticalScrollIndicator = false
        tableview.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf._getConversations()

        }
        return tableview
    }()
    fileprivate lazy var errorTips: JCNetworkTipsCell = JCNetworkTipsCell()
    fileprivate var showNetworkTips = false
    
    fileprivate lazy var titleTips: UILabel = {
        var tips = UILabel(frame: CGRect(x: 23, y: 0, width: 67, height: 44))
        tips.font = UIFont.systemFont(ofSize: 18)
        tips.textColor = UIColor.white
        tips.textAlignment = .left
        tips.backgroundColor = UIColor(hex: 0x5AD4D3)
        return tips
    }()

    fileprivate lazy var titleTipsView: UIView = {
        var view = UIView(frame: CGRect(x: self.view.width / 2 - 45, y: 20, width: 90, height: 44))
        view.backgroundColor =  UIColor(hex: 0x5AD4D3)
        let activityView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 12, width: 20, height: 20))
        view.addSubview(activityView)
        activityView.startAnimating()
        view.addSubview(self.titleTips)
        view.isHidden = true
        return view
    }()
    
    //Mark: - private func
    private func _init() {
        view.backgroundColor = UIColor.theme.background
        if #available(iOS 10.0, *) {
            navigationController?.tabBarItem.badgeColor = UIColor(hex: 0xEB424C)
        }

        let appDelegate = UIApplication.shared.delegate
        let window = appDelegate?.window!
        window?.addSubview(titleTipsView)
        
        _setupNavigation()
        JMessage.add(self, with: nil)
        view.addSubview(tableview)
        view.addSubview(friendRequestView)
        
        friendRequestView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight)
            make.height.equalTo(64)
        }
        
        tableview.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(friendRequestView.snp.bottom)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: NSNotification.Name(rawValue: "kNetworkReachabilityChangedNotification"), object: nil)

        _getConversations()
        NotificationCenter.default.addObserver(self, selector: #selector(_getConversations), name: NSNotification.Name(rawValue: kUpdateConversation), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connectClose), name: NSNotification.Name.jmsgNetworkDidClose, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connectSucceed), name: NSNotification.Name.jmsgNetworkDidLogin, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connecting), name: NSNotification.Name.jmsgNetworkIsConnecting, object: nil)
        
        tableview.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }
    
    @objc func reachabilityChanged(note: NSNotification) {
        if let curReach = note.object as? Reachability {
            let status = curReach.currentReachabilityStatus()
            switch status {
            case NotReachable:
                notReachable()
            default :
                reachable()
            }
        }
    }
    
    private func _setupNavigation() {
        addButton.addTarget(self, action: #selector(_clickNavRightButton(_:)), for: .touchUpInside)
        addButton.setImage(UIImage.loadImage("com_icon_add"), for: .normal)
        let item = UIBarButtonItem(customView: addButton)
        navigationItem.rightBarButtonItem =  item
    }
    
    func _updateBadge() {
        var count = datas.unreadCount
        let ddd = datas.notFfriendUnreadCount
        if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
            let badgeCount = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
            count += badgeCount
        }
        
        if count > 99 {
            navigationVC?.tabBarItem.badgeValue = "99+"
        } else {
            navigationVC?.tabBarItem.badgeValue = count - ddd == 0 ? nil : "\(count - ddd)"
        }
    }
    
    @objc func _getConversations() {
        JMSGConversation.allConversations { (result, error) in
            guard let conversatios = result else {
                return
            }
            self.datas = conversatios as! [JMSGConversation]
            self.datas = self.sortConverstaions(self.datas)
            self.filterNotFriendConversation()
            self.tableview.reloadData()
//            if self.datas.count == 0 {
//                self.emptyView.isHidden = false
//            } else {
//                self.emptyView.isHidden = true
//            }
            self._updateBadge()
        }
    }
    /// 过滤非好友聊天会话消息 - 俱乐部 / 好友聊天
    private func filterNotFriendConversation() {
        self.datas = self.datas.filter { (conversation) -> Bool in
            /// 过滤非好友关系的会话
            if let target: JMSGUser = conversation.target as? JMSGUser, !target.isFriend, target.username != UserCenter.default.customerUserName, JMSGUser.myInfo().username != UserCenter.default.customerUserName {
                return false
            }
            /// 过滤俱乐部会话 如果群组描述中包含 "|.>p_t_g<.|" 则为聚会任务群
            if let target: JMSGGroup = conversation.target as? JMSGGroup, let desc = target.desc, !desc.contains("|.>p_t_g<.|") {
                return false
            }
            return true
        }
    }

    fileprivate func sortConverstaions(_ convs: [JMSGConversation]) -> [JMSGConversation] {
        var stickyConvs: [JMSGConversation] = []
        var allConvs: [JMSGConversation] = []
        for index in 0..<convs.count {
            let conv = convs[index]
            if conv.ex.isSticky {
                stickyConvs.append(conv)
            } else {
                allConvs.append(conv)
            }
        }

        stickyConvs = stickyConvs.sorted(by: { (c1, c2) -> Bool in
            c1.ex.stickyTime > c2.ex.stickyTime
        })

        allConvs.insert(contentsOf: stickyConvs, at: 0)
        return allConvs
    }
    
    //MARK: - click func
    @objc func _clickNavRightButton(_ sender: UIButton) {
        _setupPopView()
    }
    
    private func _setupPopView() {
        presentPopupView(selectView)
    }
    
    fileprivate lazy var selectView: YHPopupView = {
        let popupView = MorePopupView(frame: CGRect(x: self.view.width - 150, y: 65, width: 145, height: 554 / 3))
        popupView.delegate = self
        return popupView
    }()
}

extension JCConversationListViewController: UITableViewDelegate, UITableViewDataSource {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return showNetworkTips ? datas.count + 1 : datas.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if showNetworkTips && indexPath.row == 0 {
            errorTips.selectionStyle = .none
            return errorTips
        }
        return tableView.dequeueReusableCell(withIdentifier: "JCConversationCell", for: indexPath)
    }
    
    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? JCConversationCell else {
            return
        }
        cell.bindConversation(datas[showNetworkTips ? indexPath.row - 1 : indexPath.row])
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if showNetworkTips && indexPath.row == 0 {
            return 40
        }
        return 64
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if showNetworkTips && indexPath.row == 0 {
            return 
        }
        let conversation = datas[showNetworkTips ? indexPath.row - 1 : indexPath.row]
        conversation.clearUnreadCount()
        guard let cell = tableView.cellForRow(at: indexPath) as? JCConversationCell else {
            return
        }
        cell.bindConversation(conversation)
        if let target: JMSGGroup = conversation.target as? JMSGGroup, let desc = target.desc, !desc.contains("|.>p_t_g<.|") {
            let vc = JCChatViewController(conversation: conversation)
            navigationVC?.pushViewController(vc, animated: true)
        } else {
            let vc = JCChatViewController(conversation: conversation, true)
            navigationVC?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
            completionHandler(true)
            self._delete(indexPath)
        }
        deleteAction.image = UIImage(named: "icon_trash")
        deleteAction.backgroundColor = UIColor(hex: 0xFFC000)
        
        
        let conversation = datas[showNetworkTips ? indexPath.row - 1 : indexPath.row]
        
        let upAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
            completionHandler(true)
            conversation.ex.isSticky = !conversation.ex.isSticky
            self._getConversations()
        }
        //upAction.image = UIImage(named: "icon_trash")
        if conversation.ex.isSticky {
            upAction.title = "取消置顶"
        } else {
            upAction.title = "置顶"
        }
        upAction.backgroundColor = UIColor(hex: 0xFFC000)
        
        
        let actions:[UIContextualAction] = [upAction, deleteAction]
        let action:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)
        action.performsFirstActionWithFullSwipe = false
        return action
    }
    
    private func _delete(_ indexPath: IndexPath) {
        let conversation = datas[indexPath.row]
        let tager = conversation.target
        JCDraft.update(text: nil, conversation: conversation)
        if conversation.ex.isGroup {
            guard let group = tager as? JMSGGroup else {
                return
            }
            JMSGConversation.deleteGroupConversation(withGroupId: group.gid)
        } else {
            guard let user = tager as? JMSGUser else {
                return
            }
            JMSGConversation.deleteSingleConversation(withUsername: user.username, appKey: user.appKey!)
        }
        datas.remove(at: indexPath.row)
//        if datas.count == 0 {
//            emptyView.isHidden = false
//        } else {
//            emptyView.isHidden = true
//        }
        tableview.reloadData()
    }
    
}

extension JCConversationListViewController: MorePopupViewDelegate {
    func popupView(view: MorePopupView, addGroup addButton: UIButton) {
        dismissPopupView()
        let vc = JCUpdateMemberViewController()
        vc.isAddMember = false
        navigationVC?.pushViewController(vc, animated: true)
    }
    
    func popupView(view: MorePopupView, addFriend addButton: UIButton) {
        dismissPopupView()
        navigationVC?.pushViewController(JCSearchFriendViewController(), animated: true)
    }
    
    func popupView(view: MorePopupView, addSingle addButton: UIButton) {
        dismissPopupView()
        let vc = JCSearchFriendViewController()
        vc.isSearchUser = true
        navigationVC?.pushViewController(vc, animated: true)
    }
    
    func popupView(view: MorePopupView, scanQRCode addButton: UIButton) {
        dismissPopupView()
        let vc = ScanQRCodeViewController()
        navigationVC?.pushViewController(vc, animated: true)
    }
}

extension JCConversationListViewController: JMessageDelegate {
    
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        _getConversations()
    }
    
    func onConversationChanged(_ conversation: JMSGConversation!) {
        _getConversations()
    }
    
    func onGroupInfoChanged(_ group: JMSGGroup!) {
        _getConversations()
    }
    
    func onSyncRoamingMessageConversation(_ conversation: JMSGConversation!) {
        _getConversations()
    }
    
    func onSyncOfflineMessageConversation(_ conversation: JMSGConversation!, offlineMessages: [JMSGMessage]!) {
        _getConversations()
    }
    
    func onReceive(_ retractEvent: JMSGMessageRetractEvent!) {
        _getConversations()
    }
    
}

//extension JCConversationListViewController: UISearchControllerDelegate {
//    func willPresentSearchController(_ searchController: UISearchController) {
//        tableview.isHidden = true
//        emptyView.isHidden = true
//        UIView.animate(withDuration: 0.35, animations: {
//            self.emptyView.frame = CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height - 64)
//        }) { (_) in
//            self.navigationVC?.tabBarController?.tabBar.isHidden = true
//        }
//    }
//    func willDismissSearchController(_ searchController: UISearchController) {
//        UIView.animate(withDuration: 0.35) {
//            self.emptyView.frame = CGRect(x: 0, y: 64 + 36, width: self.view.width, height: self.view.height - 64 - 36)
//        }
//        tableview.isHidden = false
//        if datas.count == 0 {
//            emptyView.isHidden = false
//        }
//        let nav = searchController.searchResultsController as! BaseNavController
//        nav.isNavigationBarHidden = true
//        nav.popToRootViewController(animated: false)
//        navigationVC?.tabBarController?.tabBar.isHidden = false
//    }
//}

// MARK: - network tips
extension JCConversationListViewController {
    
    func reachable() {
        if !showNetworkTips {
            return
        }
        showNetworkTips = false
        tableview.reloadData()
    }
    
    func notReachable() {
        if showNetworkTips {
            return
        }
        showNetworkTips = true
        if datas.count > 0 {
            let indexPath = IndexPath(row: 0, section: 0)
            tableview.beginUpdates()
            tableview.insertRows(at: [indexPath], with: .automatic)
            tableview.endUpdates()
        } else {
            tableview.reloadData()
        }
    }
    
    @objc func connectClose() {
        isConnecting = false
        DispatchQueue.main.async {
            self.titleTipsView.isHidden = true
        }
    }
    
    @objc func connectSucceed() {
        isConnecting = false
        DispatchQueue.main.async {
            self.titleTipsView.isHidden = true
        }
    }
    
    @objc func connecting() {
        _connectingSate()
    }
    
    func _connectingSate() {
        let window = UIApplication.shared.delegate?.window
        if let window = window {
            guard let rootViewController = window?.rootViewController as? JCMainTabBarController else {
                return
            }
            guard let nav = rootViewController.selectedViewController as? BaseNavController else {
                return
            }
            guard let currentVC = nav.topViewController else {
                return
            }
            if currentVC.isKind(of: JCConversationListViewController.self) {
                isConnecting = true
                titleTips.text = "连接中"
                titleTipsView.isHidden = false
            }
        }
    }
}

extension JCConversationListViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return UIScrollView()
    }
}


extension JCConversationListViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}

extension JCConversationListViewController: MTDiscoverFriendRequestViewDelegate {
    
    func didTapFriendRequestEntrance() {
        UserDefaults.standard.set(0, forKey: kUnreadInvitationCount)
        self.friendRequestView.setRedPoint(pointValue: 0)
        self.navigationVC?.pushViewController(MTFriendViewRequestVerifyController(friendRequestType: .single), animated: true)
        JCVerificationInfoDB.shareInstance.updateAllUnReadRequestMessage(verType: 1)
        
    }
    
}
